package pers.vic.netty.echo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import pers.vic.netty.echo.client.handler.EchoClientHandler;

import java.net.InetSocketAddress;

/**
 * 描述:引导客户端
 * @author Vic.xu
 * @date 2021-11-22 17:17
 */
public class EchoClient {

    private final String host;

    private final int port;


    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) throws InterruptedException {
        if (args.length != 2) {
            System.err.println("Usage: " + EchoClient.class.getSimpleName() + " <host> <port>");
        }
        String host = args[0];
        int port = Integer.parseInt(args[1]);
        new EchoClient(host, port).start();


    }

    private void start() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            //指定EventLoopGroup以处理客户端时间，需要适用于NIO的实现
            Bootstrap b = new Bootstrap();
            b.group(group)
                    //适用于NIO传输的Channel类型
                    .channel(NioSocketChannel.class)
                    //设置服务器的InetSocketAddress
                    .remoteAddress(new InetSocketAddress(host, port))
                    //在穿件channel时， 向channelPipe
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoClientHandler());
                        }
                    });
            //连接到远程节点  阻塞等待直到连接完成
            ChannelFuture f = b.connect().sync();
            //阻塞 直到Channel关闭
            f.channel().closeFuture().sync();

        }finally {
            //关闭线程池 并且释放所有的资源
            group.shutdownGracefully();

        }
    }

}
